import React, { Component } from 'react'
import RouterView from '../router';
import { NavLink } from 'react-router-dom'
import { connect } from 'react-redux';
import * as Actions from '../store/actions';

const List = class List extends Component {
  componentWillMount() {
    if (Object.keys(this.props.list).length === 0) {
      this.props.getList();
    }
  }
  goto(item) {
    this.props.history.push('/page/detail/' + item.id, { item });
  }

  render() {
    let { list } = this.props;
    return (
      <div>
        list 页面
        {Object.keys(list).map(
          (type, i) => {
            return <div className="block" key={i}>{type}
              <ul>
                {list[type].map((v) => {
                  return (<li key={v.id} >
                    <h3> {v.name}</h3>
                    <img src={v.image} alt={v.name} onClick={() => {
                      this.goto(v)
                    }} />

                    <p>库存: {v.stock}</p>

                    <p><span onClick={() => {
                      v.num--;
                      if (v.num < 0) {
                        v.num = 0;
                      }
                      this.props.setList(list);
                    }}>-</span>{v.num}<span onClick={() => {
                      if (v.stock > 0) {
                        v.num++;
                        v.stock--;
                      }
                      this.props.setList(list);

                    }}>+</span></p>

                  </li>)
                })}
              </ul>
            </div>
          }
        )}

        <NavLink to="/main/list/lista">LIST A</NavLink>
        <NavLink to="/main/list/listb">LIST B</NavLink>
        <RouterView routes={this.props.routes}></RouterView>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    ...state
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    setList(data) {
      dispatch({ type: 'SET_LIST', data })
    },
    getList() {
      dispatch(Actions.getList());
    }

  }
}

export default connect(mapStateToProps, mapDispatchToProps)(List)